<template>
  <div class="personal-center">
    <a-card class="general-card">
      <!-- 头部用户信息区域 -->
      <div class="user-profile">
        <div class="avatar-container">
          <div class="avatar-wrapper">
            <input type="file" id="avatar-upload" accept="image/png, image/jpeg, image/gif" class="hidden-input"
              @change="handleFileChange" />
            <UserAvatar :avatar="userInfo.avatar" :username="userInfo.username" :size="120" />
            <div class="avatar-hover-mask" @click="triggerFileInput">
              <icon-camera />
              <span>点击更换头像</span>
            </div>
          </div>
        </div>
        <div class="user-details">
          <h2 class="username">{{ userInfo.nickname || userInfo.username }}</h2>
          <div class="user-tags">
            <a-tag color="blue" v-if="userInfo.role && userInfo.role.name === 'admin'">管理员</a-tag>
            <a-tag color="blue" v-else-if="userInfo.roles && userInfo.roles.includes('admin')">管理员</a-tag>
            <a-tag color="blue" v-else-if="userInfo.role_id === 1">管理员</a-tag>
            <a-tag color="green" v-else>员工</a-tag>
          </div>
        </div>
      </div>

      <a-divider />

      <!-- 基本信息部分 -->
      <div class="info-section">
        <div class="section-header">
          <h3 class="section-title">基本信息</h3>
          <div class="action-buttons">
            <a-button type="primary" @click="toggleEditMode" v-if="!isEditing">
              修改信息
            </a-button>
            <a-button type="primary" @click="submitUserInfo" v-else>
              保存信息
            </a-button>
            <a-button type="outline" @click="showPasswordModal = true" style="margin-left: 8px;">
              修改密码
            </a-button>
          </div>
        </div>

        <a-form ref="userForm" :model="userInfo" :rules="rules" class="user-form">
          <a-form-item field="username" label="用户名">
            <a-input v-model="userInfo.username" placeholder="请输入用户名" :disabled="true" />
          </a-form-item>

          <a-form-item field="nickname" label="昵称" :validate-trigger="['change', 'blur']">
            <a-input v-model="userInfo.nickname" placeholder="请输入昵称" :disabled="!isEditing" />
          </a-form-item>

          <a-form-item field="email" label="邮箱" :validate-trigger="['change', 'blur']">
            <a-input v-model="userInfo.email" placeholder="请输入邮箱" :disabled="!isEditing" />
          </a-form-item>

          <a-form-item field="phone" label="手机号" :validate-trigger="['change', 'blur']">
            <a-input v-model="userInfo.phone" placeholder="请输入手机号" :disabled="!isEditing" />
          </a-form-item>
        </a-form>
      </div>
    </a-card>

    <!-- 修改密码弹窗 -->
    <a-modal v-model:visible="showPasswordModal" title="修改密码" @cancel="resetPasswordForm">
      <a-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" layout="vertical">
        <a-form-item field="oldPassword" label="原密码" :validate-trigger="['change', 'blur']">
          <a-input-password v-model="passwordForm.oldPassword" placeholder="请输入原密码" />
        </a-form-item>
        <a-form-item field="newPassword" label="新密码" :validate-trigger="['change', 'blur']">
          <a-input-password v-model="passwordForm.newPassword" placeholder="请输入新密码" />
        </a-form-item>
        <a-form-item field="confirmPassword" label="确认密码" :validate-trigger="['change', 'blur']">
          <a-input-password v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
        </a-form-item>
      </a-form>
      <template #footer>
        <a-button @click="resetPasswordForm">取消</a-button>
        <a-button type="primary" :loading="passwordLoading" @click="handleUpdatePassword">确定</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { Message } from '@arco-design/web-vue';
import { useUserStore } from '@/stores/user';
import { IconCamera, IconHistory } from '@arco-design/web-vue/es/icon';
import UserAvatar from '@/components/UserAvatar.vue';
import userApi from '@/api/user';

const userStore = useUserStore();
const hasAvatar = ref(true);
const isEditing = ref(false);
const showPasswordModal = ref(false);
const loading = ref(false);
const passwordLoading = ref(false);

// 用户信息
const userInfo = reactive({
  username: '未设置',
  nickname: '未设置',
  role: null,        // 角色对象
  role_id: 0,        // 角色ID
  roles: [],         // 角色名称数组
  email: '未设置',
  phone: '未设置',
  avatar: userStore.avatar || '',
});

// 密码修改表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 表单引用
const userForm = ref(null);
const passwordFormRef = ref(null);

// 表单校验规则
const rules = {
  nickname: [
    { required: true, message: '请输入昵称' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址' },
    { type: 'email', message: '邮箱格式不正确' }
  ],
  phone: [
    { required: true, message: '请输入手机号码' },
    { match: /^1[3-9]\d{9}$/, message: '手机号格式不正确' }
  ]
};

// 密码表单校验规则
const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码' },
    { minLength: 6, message: '密码长度不能少于6个字符' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码' },
    { minLength: 6, message: '密码长度不能少于6个字符' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码' },
    {
      validator: (value, cb) => {
        if (value !== passwordForm.newPassword) {
          return cb('两次输入的密码不一致');
        }
        return cb();
      }
    }
  ]
};

// 切换编辑模式
function toggleEditMode() {
  isEditing.value = !isEditing.value;

  // 进入编辑模式时，清空"未设置"的字段
  if (isEditing.value) {
    if (userInfo.nickname === '未设置') userInfo.nickname = '';
    if (userInfo.email === '未设置') userInfo.email = '';
    if (userInfo.phone === '未设置') userInfo.phone = '';
  } else {
    // 退出编辑模式时，恢复未填写的字段为"未设置"
    if (!userInfo.nickname) userInfo.nickname = '未设置';
    if (!userInfo.email) userInfo.email = '未设置';
    if (!userInfo.phone) userInfo.phone = '未设置';
  }
}

// 提交表单 - 更新用户信息
const submitUserInfo = async () => {
  loading.value = true;

  try {
    // 首先确保所有必填字段都有值
    if (!userInfo.nickname || userInfo.nickname === '未设置') {
      Message.error('请输入昵称');
      loading.value = false;
      return;
    }

    if (!userInfo.email || userInfo.email === '未设置') {
      Message.error('请输入邮箱地址');
      loading.value = false;
      return;
    }

    if (!userInfo.phone || userInfo.phone === '未设置') {
      Message.error('请输入手机号码');
      loading.value = false;
      return;
    }

    // 验证邮箱格式
    if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(userInfo.email)) {
      Message.error('邮箱格式不正确');
      loading.value = false;
      return;
    }

    // 验证手机号格式
    if (!/^1[3-9]\d{9}$/.test(userInfo.phone)) {
      Message.error('手机号格式不正确');
      loading.value = false;
      return;
    }

    // 构建更新数据
    const updateData = {
      nickname: userInfo.nickname,
      email: userInfo.email,
      phone: userInfo.phone,
      avatar: userInfo.avatar || userStore.avatar
    };


    // 调用API更新用户信息
    Message.loading({ content: '正在保存信息...', duration: 0 });
    const res = await userApi.updateUserInfo(updateData);


    Message.clear();
    if (res.code === 200 || res.code === 0) {
      Message.success('个人信息更新成功');
      // 切换回非编辑模式
      isEditing.value = false;
      // 保存当前头像状态和值
      const currentAvatar = userInfo.avatar;
      const currentHasAvatar = hasAvatar.value;
      // 静默刷新用户信息（不显示成功提示）
      await refreshUserInfo(false);
      // 如果之前有头像，保持头像状态不变
      if (currentHasAvatar) {
        hasAvatar.value = true;
        userInfo.avatar = currentAvatar;
      }
    } else {
      Message.error(res.message || '更新失败，请重试');
    }
  } catch (error) {
    Message.error('更新失败: ' + (error.message || '未知错误'));
  } finally {
    loading.value = false;
  }
};

// 刷新用户信息
const refreshUserInfo = async (showSuccessMessage = true) => {
  try {
    const res = await userApi.getUserInfo();

    if (res.code === 200 || res.code === 0) {
      // 保存当前头像状态
      const currentAvatar = userInfo.avatar;
      const currentHasAvatar = hasAvatar.value;

      // 更新用户信息
      userInfo.username = res.data.username || '未设置';
      userInfo.nickname = res.data.nickname || '未设置';
      userInfo.email = res.data.email || '未设置';
      userInfo.phone = res.data.phone || '未设置';
      userInfo.role_id = res.data.role_id || 0;

      // 处理角色对象
      if (res.data.role) {
        userInfo.role = res.data.role;

        // 如果角色对象包含name属性，添加到roles数组
        if (res.data.role.name) {
          userInfo.roles = [res.data.role.name];

        }
      }
      // 如果没有角色对象，则根据角色ID推断
      else if (res.data.role_id) {
        userInfo.roles = [res.data.role_id === 1 ? 'admin' : 'staff'];

      }

      // 头像处理 - 直接使用原始路径
      userInfo.avatar = res.data.avatar || '';


      // 更新角色信息
      if (res.data.roles) {
        userInfo.roles = Array.isArray(res.data.roles) ? res.data.roles : [res.data.roles];
      } else if (res.data.role_name) {
        userInfo.roles = [res.data.role_name];
      } else if (res.data.role) {
        userInfo.roles = [res.data.role];
      }

      console.log('刷新后的用户信息:', userInfo);

      // 更新store中的用户信息，保留头像，但确保头像格式正确
      const userData = { ...res.data };
      // 使用store中的processAvatarUrl函数处理头像
      userData.avatar = userStore.processAvatarUrl ? userStore.processAvatarUrl(userInfo.avatar) : userInfo.avatar;
      console.log('处理后的头像路径:', userData.avatar);
      userStore.setUserInfo(userData);

      // 只在需要时显示成功提示
      if (showSuccessMessage) {
        Message.success('获取用户信息成功');
      }

      return true;
    } else {
      Message.error(res.message || '获取用户信息失败');
      return false;
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    Message.error('获取用户信息失败: ' + (error.message || '未知错误'));
    return false;
  }
};

// 获取头像文字
function getAvatarText(name) {
  if (!name) return 'U';
  // 如果是中文，取第一个字
  if (/[\u4e00-\u9fa5]/.test(name.charAt(0))) {
    return name.charAt(0);
  }
  // 如果是英文，取首字母大写
  return name.charAt(0).toUpperCase();
}

// 处理头像URL，确保URL正确并添加时间戳（避免缓存）
function processAvatarUrl(url) {
  if (!url) return '';

  // 如果是assets开头的默认头像，直接返回空字符串使用文字头像
  if (url.includes('/assets/default-avatar')) {
    console.log('检测到默认头像，返回空');
    return '';
  }

  console.log('处理头像路径，原始URL:', url);

  // 去除可能存在的时间戳参数
  let cleanUrl = url;
  if (url.includes('?')) {
    cleanUrl = url.substring(0, url.indexOf('?'));
    console.log('移除时间戳后的URL:', cleanUrl);
  }

  // 移除可能存在的/api/v1前缀
  if (cleanUrl.includes('/api/v1')) {
    cleanUrl = cleanUrl.replace('/api/v1', '');
    console.log('移除api/v1前缀后的URL:', cleanUrl);
  }

  // 确保URL统一格式 - 确保以/开头
  if (!cleanUrl.startsWith('/') && !cleanUrl.startsWith('http')) {
    cleanUrl = '/' + cleanUrl;
  }

  // 如果是完整URL则直接使用
  if (cleanUrl.startsWith('http://') || cleanUrl.startsWith('https://')) {
    // 不添加时间戳，避免每次都重新加载图片
    return cleanUrl;
  }

  // 获取API基础URL
  const baseApiUrl = import.meta.env.VITE_API_BASE_URL || '';
  const baseUrl = baseApiUrl.endsWith('/') ? baseApiUrl.slice(0, -1) : baseApiUrl;

  // 如果baseUrl为空，直接返回cleanUrl
  if (!baseUrl) {
    console.log('API基础URL为空，直接返回:', cleanUrl);
    return cleanUrl;
  }

  // 拼接基础URL和相对路径
  const fullUrl = baseUrl + cleanUrl;
  console.log('处理后的头像URL:', fullUrl);

  return fullUrl;
}

// 根据用户名生成头像背景颜色
function getAvatarColor(name) {
  const colors = [
    '#1890ff', '#36cfc9', '#52c41a', '#faad14', '#f5222d',
    '#722ed1', '#eb2f96', '#fa8c16', '#a0d911', '#13c2c2'
  ];

  if (!name) return colors[0];

  // 使用用户名的字符码之和作为颜色索引
  const sum = name.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0);
  const index = sum % colors.length;

  return colors[index];
}

// 处理头像加载错误
function handleAvatarError(e) {
  hasAvatar.value = false;
}

// 重置密码表单
function resetPasswordForm() {
  passwordForm.oldPassword = '';
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  showPasswordModal.value = false;
}

// 修改密码
const handleUpdatePassword = async () => {
  if (!passwordFormRef.value) return;
  passwordLoading.value = true;

  try {
    // 手动验证表单的每一个字段
    let hasError = false;

    // 验证原密码
    if (!passwordForm.oldPassword || passwordForm.oldPassword.length < 6) {
      Message.error('请输入至少6位的原密码');
      hasError = true;
    }

    // 验证新密码
    if (!passwordForm.newPassword || passwordForm.newPassword.length < 6) {
      Message.error('请输入至少6位的新密码');
      hasError = true;
    }

    // 验证确认密码
    if (passwordForm.newPassword !== passwordForm.confirmPassword) {
      Message.error('两次输入的密码不一致');
      hasError = true;
    }

    if (hasError) {
      passwordLoading.value = false;
      return;
    }

    // 准备请求数据
    const passwordData = {
      old_password: passwordForm.oldPassword,
      new_password: passwordForm.newPassword
    };

    // 关闭模态框并立即显示处理中提示
    showPasswordModal.value = false;

    // 清空表单
    passwordForm.oldPassword = '';
    passwordForm.newPassword = '';
    passwordForm.confirmPassword = '';

    // 显示加载提示
    const loadingInstance = Message.loading({
      content: '正在处理密码修改请求...',
      duration: 0
    });

    try {
      console.log('正在调用密码修改API...');
      // 调用修改密码API
      const result = await userStore.updatePassword(passwordData);
      console.log('密码修改API返回结果:', result);

      // 关闭加载提示
      loadingInstance.close();

      if (result && result.success) {
        // 密码修改成功
        console.log('密码修改成功，准备登出并跳转');

        // 显示成功提示
        Message.success({
          content: '密码修改成功，即将退出登录...',
          duration: 2000
        });

        // 延迟登出操作
        setTimeout(async () => {
          console.log('执行登出操作...');
          // 使用userStore的logout方法进行正确的登出操作，该方法会:
          // 1. 清除本地存储的用户数据
          // 2. 重置路由
          // 3. 调用登出API
          // 4. 跳转到登录页面
          await userStore.logout();
        }, 2000);
      } else {
        // 密码修改失败
        console.error('密码修改失败:', result);
        Message.error({
          content: result?.message || '密码修改失败',
          duration: 3000
        });
      }
    } catch (error) {
      // 关闭加载提示
      loadingInstance.close();

      console.error('密码修改过程中出错:', error);
      Message.error({
        content: '密码修改失败: ' + (error?.message || '未知错误'),
        duration: 3000
      });
    }
  } catch (error) {
    console.error('表单验证过程中出错:', error);
    Message.error('操作异常，请重试');
  } finally {
    passwordLoading.value = false;
  }
};

// 处理文件变化
function handleFileChange(event) {
  const file = event.target.files[0];
  if (file) {
    // 验证文件类型
    const isJpgOrPng = ['image/jpeg', 'image/png', 'image/gif'].includes(file.type);
    if (!isJpgOrPng) {
      Message.error('头像只能是JPG/PNG/GIF格式!');
      return;
    }

    // 验证文件大小
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      Message.error('头像不能超过2MB!');
      return;
    }

    handleAvatarUpload({ file });
  }
}

// 处理头像上传
async function handleAvatarUpload(options) {
  const { file, onSuccess, onError } = options;
  
  // 显示上传中状态
  const loadingMessage = Message.loading({
    content: '正在上传头像...',
    duration: 0
  });

  try {
    const formData = new FormData();
    formData.append('file', file);

    // 使用userStore中的方法上传头像
    const response = await userStore.updateAvatar(formData);
    console.log('上传头像响应:', response);
    
    // 关闭加载提示
    loadingMessage.close();

    if (response && (response.code === 200 || response.code === 0) && response.data) {
      // 显示成功消息
      Message.success('头像上传成功，请手动刷新页面查看效果');

      if (onSuccess) onSuccess(response);
    } else {
      const errorMsg = response?.message || response?.msg || '头像上传失败';
      console.error('头像上传失败:', errorMsg);
      Message.error(errorMsg, 3000);
      if (onError) onError(new Error(errorMsg));
    }
  } catch (error) {
    // 关闭加载提示
    loadingMessage.close();
    console.error('头像上传出错:', error);
    Message.error('头像上传失败，请稍后重试 - ' + (error.message || '未知错误'), 3000);
    if (onError) onError(error);
  }
}

// 触发文件输入
function triggerFileInput() {
  const fileInput = document.getElementById('avatar-upload');
  if (fileInput) {
    fileInput.click();
  }
}

// 页面加载时获取最新用户信息
onMounted(async () => {


  // 直接调用API获取最新用户信息
  try {
    const res = await userApi.getUserInfo();


    if (res.code === 200 || res.code === 0) {
      // 更新用户信息
      userInfo.username = res.data.username || '未设置';
      userInfo.nickname = res.data.nickname || '未设置';
      userInfo.email = res.data.email || '未设置';
      userInfo.phone = res.data.phone || '未设置';
      userInfo.role_id = res.data.role_id || 0;

      // 处理角色对象
      if (res.data.role) {
        userInfo.role = res.data.role;
        console.log('保存角色对象:', userInfo.role);
        // 如果角色对象包含name属性，添加到roles数组
        if (res.data.role.name) {
          userInfo.roles = [res.data.role.name];
          console.log('从角色对象中提取角色名称:', userInfo.roles);
        }
      }
      // 如果没有角色对象，则根据角色ID推断
      else if (res.data.role_id) {
        userInfo.roles = [res.data.role_id === 1 ? 'admin' : 'staff'];
        console.log('根据角色ID推断角色:', userInfo.roles);
      }

      // 头像处理 - 直接使用原始路径
      userInfo.avatar = res.data.avatar || '';
      console.log('设置头像路径:', userInfo.avatar);

      // 更新store
      userStore.setUserInfo({ ...res.data });
      console.log('已更新store中的用户信息');

      Message.success('获取用户信息成功');
    } else {
      Message.error(res.message || '获取用户信息失败');
    }
  } catch (error) {
    console.error('获取用户信息失败:', error);
    Message.error('获取用户信息失败: ' + (error.message || '未知错误'));
  }
});
</script>

<style lang="less" scoped>
@import '@/styles/variables.less';

.personal-center {
  padding: @spacing-xl;
}

.general-card {
  box-shadow: @box-shadow-base;
}

.user-profile {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  margin-bottom: @spacing-xl;
  padding: @spacing-xl 0;
  text-align: center;
}

.avatar-upload {
  :deep(.arco-upload-trigger) {
    background: none;
    border: none;
    padding: 0;
    width: auto;
    height: auto;
    display: block;
  }

  :deep(.arco-upload-trigger-text) {
    display: none;
  }
}

.avatar-container {
  position: relative;
  cursor: pointer;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 16px;
}

.hidden-input {
  position: absolute;
  width: 0;
  height: 0;
  opacity: 0;
  cursor: pointer;
  z-index: -1;
}

.avatar-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  border-radius: 50%;
  overflow: hidden;
  width: 120px;
  height: 120px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;

  &:hover {
    box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
    transform: translateY(-2px);
  }

  &:hover .avatar-hover-mask {
    opacity: 1;
  }

  .arco-avatar {
    width: 100%;
    height: 100%;
    border: 2px solid transparent;
    z-index: 5;
  }
}

.avatar-hover-mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
  color: white;
  border-radius: 50%;
  z-index: 10;
  backdrop-filter: blur(2px);

  .arco-icon {
    font-size: 24px;
    margin-bottom: 4px;
  }

  span {
    font-size: 12px;
    font-weight: 500;
  }
}

.user-details {
  text-align: center;
  margin-top: 16px;

  .username {
    font-size: 24px;
    font-weight: 500;
    margin: 8px 0;
    color: var(--color-text-1);
  }

  .user-tags {
    margin-top: 8px;
    display: flex;
    justify-content: center;
    gap: 8px;
  }
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: @spacing-lg;

  .action-buttons {
    display: flex;
    gap: 8px;
  }
}

.section-title {
  font-size: @font-size-lg;
  font-weight: 500;
  color: @text-primary;
  padding-left: @spacing-base;
  border-left: 3px solid @primary-color;
  margin: 0;
}

.info-section {
  margin-bottom: @spacing-xxl;

  .user-form {
    max-width: 500px;
    margin: 0 auto;

    .arco-form-item {
      margin-bottom: 24px;

      .arco-form-item-label-col {
        text-align: left;
      }
    }
  }
}

.arco-divider {
  margin: @spacing-xl 0;
}

@media (max-width: @screen-sm) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: @spacing-base;
  }
}
</style>